package top.itaso.app.ui.floating;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import top.itaso.app.R;
import top.itaso.lib.alog.ALog;
import top.itaso.lib.common.AppUtils;
import top.itaso.lib.common.ToastUtils;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link FloatingWindowFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FloatingWindowFragment extends Fragment {
    private static final String TAG = FloatingWindowFragment.class.getSimpleName();


    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private WindowManager mWindowManager;
    private FloatingWindowView mFloatingWindowView;

    private FloatingWindowService mFloatingWindowService;

    private TextView mBtnFloatingService;

    private ActivityResultLauncher<Intent> mStartActivitylaunch;

    public FloatingWindowFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FloatingWindowFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static FloatingWindowFragment newInstance(String param1, String param2) {
        FloatingWindowFragment fragment = new FloatingWindowFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
            ALog.vTag(TAG, "mParam1: %s,mParam2: %s", mParam1, mParam2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_floating_window, container, false);

        rootView.findViewById(R.id.btn_floating_activity).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mFloatingWindowView == null) {
                    initFloatingWindowView();
                }
                if (mFloatingWindowView.isAttachedToWindow()) {
                    mWindowManager.removeView(mFloatingWindowView);
                } else {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // Settings.canDrawOverlays > Android 8.0
//                        解决 android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W@736c577 -- permission denied for window type 2038
                        if (!Settings.canDrawOverlays(requireContext())) {
                            ToastUtils.getInstance().showShortToast(requireContext(), "请先授权:在其他应用上层显示");
                            try {
                                mStartActivitylaunch.launch(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + requireContext().getPackageName())));
                                return;
                            } catch (ActivityNotFoundException e) {
                                ALog.eTag(TAG, "无法启动 %s", "act=android.settings.action.MANAGE_OVERLAY_PERMISSION");
                                ToastUtils.getInstance().showShortToast(requireContext(), "无法启动 系统设置-显示在其他应用的上层");
                                return;
                            }


                        }
                    }
                    mWindowManager.addView(mFloatingWindowView, mFloatingWindowView.getFloatingWindowLayoutParams());
                }
            }
        });
        mBtnFloatingService = rootView.findViewById(R.id.btn_floating_service);
        mBtnFloatingService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (!Settings.canDrawOverlays(requireContext())) {
                        ToastUtils.getInstance().showShortToast(requireContext(), "请先授权:在其他应用上层显示");
                        try {
                            mStartActivitylaunch.launch(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + requireContext().getPackageName())));
//                        startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + requireContext().getPackageName())), 0);
                            return;
                        } catch (ActivityNotFoundException e) {
                            ALog.eTag(TAG, "无法启动 %s", "act=android.settings.action.MANAGE_OVERLAY_PERMISSION");
                            ToastUtils.getInstance().showShortToast(requireContext(), "无法启动 系统设置-显示在其他应用的上层");
                            return;
                        }
                    }
                }
                Intent serviceIntent = new Intent(requireContext(), FloatingWindowService.class);
                if (AppUtils.isServiceWorked(requireContext(), "top.itaso.app.ui.floating." + FloatingWindowService.class.getSimpleName())) {
                    requireContext().stopService(serviceIntent);
                    return;
                }
                if (mFloatingWindowService == null) {
                    mFloatingWindowService = new FloatingWindowService();
                }
                requireContext().startService(serviceIntent);
            }
        });
        return rootView;
    }

//    private static final int REQUESTCODE_OVERLAY_PERMISSION = 0;
//    /**
//     * 执行 startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + requireContext().getPackageName())), 0); 之后页面返回的回调
//     *
//     * @param requestCode
//     * @param resultCode
//     * @param data
//     */
//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (requestCode == REQUESTCODE_OVERLAY_PERMISSION) {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                if (!Settings.canDrawOverlays(requireContext())) {
//                    ToastUtils.getInstance().showShortToast(requireContext(), "授权失败");
//                } else {
//                    ToastUtils.getInstance().showShortToast(requireContext(), "授权成功");
//                    mBtnFloatingService.performClick();
//                }
//            }
//
//        }
//    }

    @Override
    public void onAttach(@NonNull Context context) {
        ALog.vTag(TAG, "context: %s", context);
        super.onAttach(context);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(requireContext())) {
                mStartActivitylaunch = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), mActivityResultCallback);
            }
        }

        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        initFloatingWindowView();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mWindowManager != null) {
            if (mFloatingWindowView != null && mFloatingWindowView.isAttachedToWindow()) {
                mWindowManager.removeView(mFloatingWindowView);
            }
            mWindowManager = null;
        }

    }

    private View initFloatingWindowView() {
        if (mFloatingWindowView == null) {
            mFloatingWindowView = new FloatingWindowView(requireContext());
            mFloatingWindowView.refreshUI("依附Activity的悬浮窗");
        }
        return mFloatingWindowView;
    }

    private ActivityResultCallback<ActivityResult> mActivityResultCallback = new ActivityResultCallback<ActivityResult>() {
        //java.lang.IllegalStateException: Fragment FloatingWindowFragment{9f9a667} (1e38bb1d-8275-42d2-b82b-2c1497a12353 id=0x7f080156) is attempting to registerForActivityResult after being created. Fragments must call registerForActivityResult() before they are created (i.e. initialization, onAttach(), or onCreate()).
        //fragment:1.3.0-alpha08 之后，需要在Fragment注册registerForActivityResult时，注册体需要写在onAttach() 或 onCreate()里

        /**
         *
         * @param result result = ActivityResult { resultCode = RESULT_CANCELED, data = null }
         */
        @Override
        public void onActivityResult(ActivityResult result) {
            ALog.dTag(TAG, "ActivityResult: %s", result.toString());
            if (result.getResultCode() == Activity.RESULT_CANCELED) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (!Settings.canDrawOverlays(requireContext())) {
                        ToastUtils.getInstance().showShortToast(requireContext(), "请先授权:请开启在 其他应用上层显示");
                    } else {
                        ToastUtils.getInstance().showShortToast(requireContext(), "在其他应用上层显示授权成功");
                        mBtnFloatingService.performClick();
                    }
                }
            }
        }
    };
}